package com.lenovo.smarttraffic.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;

import java.util.List;

public class SplashAdapter extends PagerAdapter {

    private FragmentActivity activity;

    private ImageView img;
    private Button btn_enter;
    private LinearLayout indicate;

    private List<Integer> imgIds;

    public SplashAdapter(@NonNull FragmentActivity activity, List<Integer> imgIds) {
        this.activity = activity;
        this.imgIds = imgIds;
    }

    @Override
    public int getCount() {
        return imgIds.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        View view = LayoutInflater.from(activity).inflate(R.layout.page_splash, null);

        initView(view);

        img.setImageResource(imgIds.get(position));

        if (position == imgIds.size() - 1) {//show button on last page
            btn_enter.setVisibility(View.VISIBLE);
            btn_enter.setOnClickListener(v -> {
                activity.getSharedPreferences(Constant.PREF, Context.MODE_PRIVATE).edit().putBoolean(Constant.PREF_FIRST_RUN, false).apply();
                activity.startActivity(new Intent(activity, MainActivity.class));
                activity.finish();
            });
        }

        //Show indicates
        for (int i = 0; i < imgIds.size(); i++) {
            ImageView imageView = new ImageView(activity);
            imageView.setPadding(10,0,10,0);
            if (i == position) {
                imageView.setImageResource(R.drawable.indicate_selected);
            } else {
                imageView.setImageResource(R.drawable.indicate);
            }
            indicate.addView(imageView);
        }

        container.addView(view);

        return view;
    }

    private void initView(View view) {
        img = view.findViewById(R.id.splash_img);
        btn_enter = view.findViewById(R.id.splash_enter);
        indicate = view.findViewById(R.id.splash_indicate);
    }

}
